<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryParamsRef" :inline="true" label-position="left" label-width="100">
      <el-form-item label="商户号" prop="merchantNoList" v-hasPermi="[9]">
        <el-select class="w-195" multiple v-model="queryParams.merchantNoList" placeholder="请选择" clearable
          style="width: 240px" @change="getList">
          <el-option v-for="item in merchantListData" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" clearable placeholder="请输入订单编号" style="width: 240px" />
      </el-form-item>
      <el-form-item v-hasPermi="[9]" label="商户订单号" prop="uniNo">
        <el-input v-model="queryParams.uniNo" clearable placeholder="请输入商户订单号" style="width: 240px" />
      </el-form-item>
      <el-form-item label="三方备注" prop="utr">
        <el-input v-model="queryParams.utr" clearable placeholder="请输入utr" style="width: 240px" />
      </el-form-item>
      <el-form-item label="三方单号" prop="utrNo">
        <el-input v-model="queryParams.utrNo" clearable placeholder="请输入三方单号" style="width: 240px" />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select class="w-195" v-model="queryParams.orderStatus" placeholder="请选择" style="width: 240px" clearable>
          <el-option key="0" label="未支付" value="1" />
          <el-option key="1" label="已支付" value="2" />
        </el-select>
      </el-form-item>
          <!-- <el-form-item label="订单开始时间" prop="startDate">
            <el-date-picker v-model="queryParams.startDate" placeholder="请选择申请开始时间" type="date" />
          </el-form-item>
          <el-form-item label="订单结束时间" prop="endDate">
            <el-date-picker  v-model="queryParams.endDate" placeholder="请选择申请结束时间" type="date" />
          </el-form-item> -->
          <el-form-item label="申请开始时间" prop="startDate">
            <el-date-picker  v-model="queryParams.startDate" placeholder="请选择申请开始时间" type="date" />
          </el-form-item>
          <el-form-item label="申请结束时间" prop="endDate">
            <el-date-picker  v-model="queryParams.endDate" placeholder="请选择申请结束时间" type="date" />
          </el-form-item>
      <!-- <el-form-item label="交易成功时间" prop="status">
         <el-col :span="10">
           <el-form-item prop="date1">
             <el-date-picker
               type="date"
               aria-label="Pick a date"
               placeholder="请选择交易开始时间"
               style="width: 100%"
             />
           </el-form-item>
         </el-col>
         <el-col class="text-center" :span="2">
           <span class="text-gray-500">-</span>
         </el-col>
         <el-col :span="10">
           <el-form-item prop="date2">
             <el-date-picker
               type="date"
               aria-label="Pick a date"
               placeholder="请选择交易结束时间"
               style="width: 100%"
             />
           </el-form-item>
         </el-col>
       </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button icon="Plus" type="warning" @click="addShow">新增</el-button>
        <el-button icon="Download" type="success" @click="outCome">导出</el-button>
        <el-button icon="Upload" type="success" @click="importClick">导入</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData">
      <!-- <el-table-column type="selection" /> -->
      <el-table-column align="center" label="商户号" prop="merchantNo" />

      <el-table-column label="订单编号" width="200" align="center" prop="orderNo" />
      <el-table-column v-hasPermi="[9]" align="center" label="商户订单号" prop="uniNo" />
      <el-table-column align="center" label="订单状态" prop="orderStatusName" />
      <el-table-column align="center" label="回调状态" prop="orderStatus" />
      <el-table-column align="center" label="订单金额" prop="orderBalance" />
      <el-table-column align="center" label="实际金额" prop="balance" />
      <el-table-column align="center" label="手续费率(%)" prop="orderRate" width="100" />
      <el-table-column align="center" label="手续费" prop="rateBalance" />
      <el-table-column align="center" label="交易方式" prop="uniChannelName" />
      <el-table-column align="center" label="申请时间" prop="applyTime" width="150"/>
      <el-table-column align="center" label="处理时间" prop="dealTime"  width="150"/>
      <el-table-column align="center" label="utr" prop="utr" />
      <el-table-column align="center" label="三方单号" prop="utrNo" />
      <!-- <el-table-column label="备注" width="200" align="center" prop="expenses" /> -->
      <el-table-column align="center" label="操作" width="180" v-hasPermi="[9]">
        <template #default="scope">
          <el-button size="small" type="warning" @click="requestHandler(scope.row)"
            v-show="scope.row.orderStatus != 2">确认
          </el-button>
          <el-button size="small" type="primary" @click="payHandler(scope.row)"
            v-show="scope.row.orderStatus != 2">复制支付链接
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <el-dialog v-model="detailShow" title="确认代收" width="50%" @close="resetHandle" destroy-on-close>
      <el-form ref="formDataRef" :model="formData" label-width="150" :rules="rules">
        <el-form-item label="订单金额">
          <el-input v-model="formData.orderBalance" disabled />
        </el-form-item>
        <el-form-item label="商户订单号">
          <el-input v-model="formData.orderNo" disabled />
        </el-form-item>
        <el-form-item label="订单手续费率(%)">
          <el-input v-model="formData.orderRate" disabled />
        </el-form-item>
        <el-form-item label="订单手续费">
          <el-input v-model="formData.rateBalance" disabled />
        </el-form-item>
        <el-form-item label="渠道名称">
          <el-input v-model="formData.uniChannelName" disabled />
        </el-form-item>
        <el-form-item label="商户订单号" prop="uniNo">
          <el-input v-model="formData.uniNo" disabled />
        </el-form-item>
        <el-form-item label="utr" prop="utr">
          <el-input v-model="formData.utr" placeholder="请输入utr" />
        </el-form-item>
        <el-form-item label="三方单号">
          <el-input v-model="formData.utrNo" disabled />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetHandle">取消
          </el-button>
          <el-button type="warning" @click="confirmHandle">确认代收</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-model="addDataShow" title="新增代收" width="50%" @close="resetHandle">
      <el-form ref="addDataRef" :model="addData" :rules="rules" label-width="150">
        <el-form-item label="订单金额" prop="orderPrice">
          <el-input v-model="addData.orderPrice" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item v-if="showUserId" label="商户编号" prop="merchantNo">
          <el-input v-model="addData.merchantNo" placeholder="请输入商户编号" />
        </el-form-item>
        <!--        <el-form-item label="utr" prop="utr">-->
        <!--          <el-input v-model="addData.utr" placeholder="请输入三方备注" />-->
        <!--        </el-form-item>-->
        <el-form-item label="商户订单号" prop="uniNo">
          <el-input v-model="addData.uniNo" placeholder="请输入商户订单号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetHandle">取消
          </el-button>
          <el-button type="warning" @click="addHandle">新增代收</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-model="importShow" title="文件导入" destroy-on-close width="400px" close-on-press-escape>
      <el-upload v-model:file-list="fileList" class="upload-demo" multiple :limit="1" :auto-upload="false"
        :on-change="handChange" style="margin-left: 65px">
        <el-button type="primary" icon="Upload">上传文件</el-button>
      </el-upload>
      <el-form ref="upDataRef" :model="upData" :rules="rules">
        <el-form-item label="通道ID" prop="uniChannelId">
          <el-input v-model="upData.uniChannelId" placeholder="请输入通道ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importShow = false">关闭</el-button>
          <el-button type="primary" @click="batchCollection">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import useUserStore from "@/store/modules/user";
import { addMerchantData, merchantData, merchantList, paymentConfirm, batchPayment } from "@/api/deal/index.js";
import { ElMessage, ElLoading } from "element-plus";
import { checkPermi } from "@/utils/permission.js";
import { download } from "@/utils/request.js";

const userStore = useUserStore();
const { proxy } = getCurrentInstance();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantNoList: [],
  },
  formData: {},
  addData: {},
  upData: {},
  rules: {
    orderPrice: [
      { required: true, message: '订单价必填！', trigger: 'blur' },

      {
        pattern: /^\d{1,9}$|^\d{1,9}[.]\d{1,2}$/,
        message: "金额为数字类型最长输入9位整数且最多保留两位小数",
        trigger: "blur"
      }
    ],
    merchantNo: [
      { required: true, message: '商户编号必填！', trigger: 'blur' }
    ],
    utr: [
      { required: true, message: '三方备注信息必填！', trigger: 'blur' }
    ],
    utrNo: [
      { required: true, message: '三方单号必填！', trigger: 'blur' }
    ],
    uniNo: [
      { required: true, message: '商户订单号必填！', trigger: 'blur' }
    ],
    uniChannelId: [
      { required: true, message: '通道id必填！', trigger: 'blur' }
    ],
  },
});
const { queryParams, form, rules, formData, addData, upData } = toRefs(data);

function handleQuery() {
  queryParams.value.pageNum = 1;
  tableData.value = []
  getList();
}

const tableData = ref([]);
const total = ref(0);


const showUserId = computed(() => {
  return checkPermi([9])
})

/** 查询参数列表 */
function getList() {
  merchantData(queryParams.value).then((res) => {
    const { total: totalNum, data } = res.data;
    tableData.value = data;
    total.value = totalNum;
  });
}

const merchantListData = ref([]);

function getMerchantList() {
  merchantList().then((res) => {
    merchantListData.value = res.data.map((item) => {
      return {
        value: item.merchantNo,
        label: item.merchantNo,
      };
    });
  });
}
// 跳转收银台
function payHandler(row) {
  // window.location.href=`http://192.168.1.6:80/home?orderNo=${row.orderNo}`
  const jumpUrl = `https://console.ftpayonline.vip/home?orderNo=${row.orderNo}&amount=${row.orderBalance}`
  let save = function (e) {
    e.clipboardData.setData('text/plain', jumpUrl)
    e.preventDefault()
  }
  document.addEventListener('copy', save)
  document.execCommand('copy')
  ElMessage({
    message: '复制成功',
    type: 'success'
  })

}
// 批量代收
const importShow = ref(false)
const fileList = ref([])
const upfile = ref()
function importClick() {
  importShow.value = true
  fileList.value = []
}
function handChange(file) {
  upfile.value = file

}
function batchCollection() {

  proxy.$refs["upDataRef"].validate((valid, fields) => {
    if (valid) {
      let fd = new FormData()
      if (upfile.value == null) {
        ElMessage.warning('请先上传文件')
        return
      }
      var file = upfile.value.raw;
      var fileName = file.name.slice(file.name.lastIndexOf('.') + 1);
      if (fileName != 'xlsx' && fileName != 'xls') {
        ElMessage.warning('文件格式错误')
        return
      }
      fd.append('file', upfile.value.raw)
      const data = {
        file: fd,
        uniChannelId: upData.value.uniChannelId
      }
      proxy.$modal.loading("正在上传文件，请稍候...");

      batchPayment(data).then((res) => {
       ElMessage.success('导入文件成功')
      //  getList()
      }).finally(() => {
        proxy.$modal.closeLoading();
      });
    }
  })
}

// 代收
const detailShow = ref(false)

function requestHandler(row) {
  formData.value = row;
  detailShow.value = true;

}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryParamsRef");
  handleQuery();
}


function confirmHandle() {
  proxy.$refs["formDataRef"].validate((valid, fields) => {
    if (valid) {
      paymentConfirm(formData.value).then((res) => {
        ElMessage.success("代收确认成功！");
        getList();
        resetHandle()
      });
    }
  })
}

function resetHandle() {
  proxy.resetForm("formDataRef");
  proxy.resetForm("addDataRef");
  detailShow.value = false;
  formData.value = {};
  addDataShow.value = false;
  addData.value = {}
}


const addDataShow = ref(false)
function addShow() {
  addDataShow.value = true;
}

//新增代收

function addHandle() {
  proxy.$refs["addDataRef"].validate((valid, fields) => {
    if (valid) {
      addMerchantData(addData.value).then((res) => {
        ElMessage.success('操作成功')
        getList();
        resetHandle()
      })
    } else {
      console.log(addData.value, 'addData.value5555')
    }
  })
}
// 代收导出
function outCome() {
  download("/merchant/payment/fee/export", queryParams.value, "代收列表.xlsx")
}
onMounted(() => {
  if (showUserId.value) {
    getMerchantList();
  }
  getList()

})
</script>
